package com.tony.util;

import com.google.common.collect.Lists;
import com.tony.entity.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.net.URL;
import java.util.List;

public class HtmlParseUtil {
    public static void main(String[] args) throws IOException {
        String url="https://search.jd.com/Search?keyword=vue";
        Document parse = Jsoup.parse(new URL(url), 30000);
        Element elementById = parse.getElementById("J_goodsList");
//        System.out.println(elementById);
        Elements lis = elementById.getElementsByTag("li");
        List<Content> contents = Lists.newArrayList();
        for(Element li:lis){
            String img = li.getElementsByTag("img").eq(0).attr("src");
            String price = li.getElementsByClass("p-price").eq(0).text();
            String name = li.getElementsByClass("p-name").eq(0).text();
            System.out.println(img);
            System.out.println(price);
            System.out.println(name);
            if(StringUtils.isEmpty(name)){
                continue;
            }
            contents.add(new Content(name,img,price));
        }
        System.out.println(contents);
    }
    public static List<Content> parseJD(String keyword){
        String url="https://search.jd.com/Search?keyword="+keyword;
        Document parse = null;
        try {
            parse = Jsoup.parse(new URL(url), 30000);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Element elementById = parse.getElementById("J_goodsList");
        Elements lis = elementById.getElementsByTag("li");
        List<Content> contents = Lists.newArrayList();
        for(Element li:lis){
            String img = li.getElementsByTag("img").eq(0).attr("src");
            String price = li.getElementsByClass("p-price").eq(0).text();
            String name = li.getElementsByClass("p-name").eq(0).text();
            if(StringUtils.isEmpty(name)){
                continue;
            }
            contents.add(new Content(name,img,price));
        }
        return contents;
    }
}
